package com.glodon.utils.util;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Created by Administrator on 2017-8-7.
 */
public class ImgCompress {
    private Image img;
    
    private int width;
    
    private int height;
    
    private String format;
    
    /**
     * 构造函数
     */
    public ImgCompress(String fileName)
        throws IOException {
        File file = new File(fileName);// 读入文件
        img = ImageIO.read(file); // 构造Image对象
        width = img.getWidth(null); // 得到源图宽
        height = img.getHeight(null); // 得到源图长
        format = StringUtils.split(fileName, '.')[1];
    }
    
    /**
     * 按照宽度还是高度进行压缩
     * 
     * @param w int 最大宽度
     * @param h int 最大高度
     */
    public byte[] resizeFix(int w, int h)
        throws IOException {
        if (width / height > w / h) {
            return resizeByWidth(w);
        } else {
            return resizeByHeight(h);
        }
    }
    
    /**
     * 以宽度为基准，等比例放缩图片
     * 
     * @param w int 新宽度
     */
    public byte[] resizeByWidth(int w)
        throws IOException {
        int h = (int)(height * w / width);

        h = h > 800 ? 800 : h;

        return resize(w, h);
    }
    
    /**
     * 以高度为基准，等比例缩放图片
     * 
     * @param h int 新高度
     */
    public byte[] resizeByHeight(int h)
        throws IOException {
        int w = (int)(width * h / height);

        w = w > 800 ? 800 : w;

        return resize(w, h);
    }
    
    /**
     * 强制压缩/放大图片到固定的大小
     * 
     * @param w int 新宽度
     * @param h int 新高度
     */
    public byte[] resize(int w, int h)
        throws IOException {
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
        // File destFile = new File("C:\\temp\\456.jpg");
        // FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
        // // 可以正常实现bmp、png、gif转jpg
        // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        // encoder.encode(image); // JPEG编码
        // out.close();
        
        return imageToBytes(image, format);
    }
    
    private byte[] imageToBytes(BufferedImage bImage, String format) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, format, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }
    
    /**
     *
     * @param filePath 需要去噪的图像
     * @throws IOException
     */
    public static InputStream cleanImage(String filePath)
        throws IOException {

        File file = new File(filePath);

        BufferedImage bufferedImage = ImageIO.read(file);
        int h = bufferedImage.getHeight();
        int w = bufferedImage.getWidth();
        
        // 灰度化
        int[][] gray = new int[w][h];
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int argb = bufferedImage.getRGB(x, y);
                // 图像加亮（调整亮度识别率非常高）
                int r = (int)(((argb >> 16) & 0xFF) * 1.1 + 30);
                int g = (int)(((argb >> 8) & 0xFF) * 1.1 + 30);
                int b = (int)(((argb >> 0) & 0xFF) * 1.1 + 30);
                if (r >= 255) {
                    r = 255;
                }
                if (g >= 255) {
                    g = 255;
                }
                if (b >= 255) {
                    b = 255;
                }
                gray[x][y] = (int)Math.pow((Math.pow(r, 2.2) * 0.2973 + Math.pow(g, 2.2) * 0.6274 + Math.pow(b, 2.2) * 0.0753), 1 / 2.2);
            }
        }
        
        // 二值化
        int threshold = ostu(gray, w, h);
        BufferedImage binaryBufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                if (gray[x][y] > threshold) {
                    gray[x][y] |= 0x00FFFF;
                } else {
                    gray[x][y] &= 0xFF0000;
                }
                binaryBufferedImage.setRGB(x, y, gray[x][y]);
            }
        }
        
        // 矩阵打印
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                if (isBlack(binaryBufferedImage.getRGB(x, y))) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
        
//        ImageIO.write(binaryBufferedImage, "jpg", new File(destDir, sfile.getName()));

        String fileType = StringUtils.split(filePath, '.')[1];

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(binaryBufferedImage, fileType, os);

        return new ByteArrayInputStream(os.toByteArray());
    }
    
    public static boolean isBlack(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() <= 300) {
            return true;
        }
        return false;
    }
    
    public static boolean isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 300) {
            return true;
        }
        return false;
    }
    
    public static int isBlackOrWhite(int colorInt) {
        if (getColorBright(colorInt) < 30 || getColorBright(colorInt) > 730) {
            return 1;
        }
        return 0;
    }
    
    public static int getColorBright(int colorInt) {
        Color color = new Color(colorInt);
        return color.getRed() + color.getGreen() + color.getBlue();
    }
    
    public static int ostu(int[][] gray, int w, int h) {
        int[] histData = new int[w * h];
        // Calculate histogram
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                int red = 0xFF & gray[x][y];
                histData[red]++;
            }
        }
        
        // Total number of pixels
        int total = w * h;
        
        float sum = 0;
        for (int t = 0; t < 256; t++)
            sum += t * histData[t];
        
        float sumB = 0;
        int wB = 0;
        int wF = 0;
        
        float varMax = 0;
        int threshold = 0;
        
        for (int t = 0; t < 256; t++) {
            wB += histData[t]; // Weight Background
            if (wB == 0)
                continue;
            
            wF = total - wB; // Weight Foreground
            if (wF == 0)
                break;
            
            sumB += (float)(t * histData[t]);
            
            float mB = sumB / wB; // Mean Background
            float mF = (sum - sumB) / wF; // Mean Foreground
            
            // Calculate Between Class Variance
            float varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);
            
            // Check if new maximum found
            if (varBetween > varMax) {
                varMax = varBetween;
                threshold = t;
            }
        }
        
        return threshold;
    }
    
}
